;
(function(w) {
  var app = new Vue({
    el: '#customerManagement',
    data: {
      listMenu: [
        {
          name: '未跟进过',
          code: 'FMWF',
          num: 0
        },
        {
          name: '跟进中',
          code: 'FMFI',
          num: 0
        },
        {
          name: '逾期未跟进',
          code: 'FMOWF',
          num: 0
        }
      ],
      selectedListMenuCode: [],
      keyWord: null,
      rperson: {
        name: null,
        list: [],
        id: null
      }, // 对接人
      rpersonKeyword: null,
      limit: ['10'],
      currentPage: 1,
      totalCount: 0,
      totalPage: 0,
      pageCounts: [{name: '10', code: '10'}, {name: '15', code: '15'}, {name: '20', code: '20'}],
      tableType: 'scroll',
      isScroll: false,
      tbTitleWidth: {
        width: 1060 + 'px'
      },
      tbTotalWidth: {
        width: 957 + 'px'
      },
      customerStatuList: [
      ],
      selectedCustomerStatu: [],
      customerType: [{
        'name': '全部',
        'code': '#'
      }, {
        'name': '公司',
        'code': 'QY'
      }, {
        'name': '个人',
        'code': 'PE'
      }],
      selectedCustomerType: [],
      industryType: [],
      selectedIndustryType: [],
      channelType: [], //渠道分类
      selectedChannelType: [],
      channelName: [], //渠道名称
      selectedChannelName: [],
      sourceList: [], //商机来源
      selectedSource: [],
      personList: [], //商机来源
      listData: [],
      countInfoData: [],
      isShowPersonLayer: false,
      isShowSelector: false,
      isShowOperationBar: true,
      isExtenseFlag: false,
      quanxian: localStorage.getItem('permissions'),
      followup_time_end: '',
      followup_time_begin: '',
      configType: 'WZ', //默认完整WZ     JD简单，WZ完整，自定义配置PZ
      module: '#',
      headArr: [],
      sortTableTitle: [],
      isScroll: false,
      isShowTableLayer: false,
      dateTimeUpdate: [],
      isActiveCode: '#',
      leftWidth: 0,
      rightWidth: 0,
      leftTableArr: [],
      rightTableArr: [],
      tbTitleWidth: {},
      listObj: {},
      lefthover: 0,
      tophover: 0,
      texthover: false,
      textLong: '',
      orders:'',
      columns:'',

      secondRowBeginDate:'',
      secondRowEndDate:'',
			
			//start
			importFlag: false,
			through: false,
			notThrough: false,
			detection: false, //检测
			detectionBtn: true,
			isShowDownload: false,
			is500: false,
    },
    filters: {
      formatYYYYMMddHHmmss(item) {
        if (!item) return '--'
        return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm:ss')
      },
      formatUndefined: function(item) {
        if (!item) return '--'
        if (typeof item == 'number') {
        	if (!isNaN(item) && item.toString().length == 13) {
        		return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
        	};
        }
        return item
      },
      customerType(item) {
        if (!item) return '--'
        return hlCodeConvert.customerType(item)
      },
      customerState(item) {
        if (!item) return '--'
        return hlCodeConvert.customerState(item)
      },
      formatIndustryType(item) {
        if (!item) return '--'
        var industryType = app.industryType.filter(el => {
          return el.code == item
        })
        return industryType[0].name
      },
      formatUndefinedFB: function(item) {
        if (!item) return '--'
        if (!isNaN(item) && item.toString().length == 13) {
          return hlDateUtil.formatUTCDate(item, 'yyyy-MM-dd HH:mm')
        };
        return item
      },
    },
    watch: {
      rpersonKeyword() {
        hlFunctionUtil.delay(() => {
          this.getRpersonData()
        }, 300)
      }
    },
    methods: {
			ZS_CUSTOMER_STATUS() {
			    var self = this
			    hlhttp.get({
			        url: 'configure/dict',
			        data: { module_code: 'ZHSH', config_name: 'ZS_CUSTOMER_STATUS' },
			        success: data => {
								data.unshift({dictName: '全部', dictCode: '#'})
			            self.customerStatuList = hlArrayUtil.replaceData(data, [{ key: 'dictName', rKey: 'name' }, { key: 'dictCode', rKey: 'code' }])
			        }
			    })
			},
			//导入
			importExcl() {
			  this.importFlag = true;
			},
			//关闭
			importExclClose() {
			  this.importFlag = false;
			  this.detection = false;
			  this.notThrough = false;
			  this.detectionBtn = true;
			  this.through = false;
			  this.srcUrl = '';
			  $('.filename-i').val('')
			},
			//导出
			customer_export () {
				hlhttp.get({
				  baseUrl: exclUrl,
				  url: 'resource/customer/_export',				  
				  success: (data) => {
				    console.log(data)
						window.open(data.url)
				  }
				})
			},
			//上传模板
			downloadxslc() {
			  $('.upload-filess').trigger('click')
			  this.detection = false;
			  this.notThrough = false;
			  this.detectionBtn = true;
			  this.through = false;
			  this.srcUrl = '';
			  $('.filename-i').val('')
			},
			//获取客户导入模板
			getExcl () {
				hlhttp.get({
				  baseUrl: exclUrl,
				  url: 'resource/customer_upload_template_excel',				  
				  success: (data) => {
				    console.log(data)
						window.open(data.url)
				  }
				})
			},
			//检测
			detectionXslx() {
			  this.detection = true;
			  this.detectionBtn = false;
			  if (!this.srcUrl) {					
					return
				};
			
			  hlhttp.put({
			    baseUrl: exclUrl,
			    url: 'resource/customer_upload_data/_check',
			    data: {
			      file_name: this.srcUrl
			    },
			    success: res => {
			      if (res.code == 200) {
			        this.detection = false;
			        this.notThrough = false;
			        this.detectionBtn = false;
			        this.through = true;
			        this.isShowDownload = true;
			        this.is500 = false;
			      }
			      if (res.code == 400) {
			        this.detection = false;
			        this.notThrough = true;
			        this.detectionBtn = false;
			        this.is500 = false;
			        this.through = false;
			        this.isShowDownload = true;
			        this.srcUrl = res.url
			      }
			      if (res.code == 500) {
			        this.is500 = true;
			        this.detection = false;
			        this.notThrough = false;
			        this.detectionBtn = false;
			        this.through = true;
			        this.srcUrl = res.url;
			        this.isShowDownload = true;
			      }
			    },
			    error: res => {
			      hl.toast('请使用标准模板上传！')
			      this.detection = false;
			      this.notThrough = true;
			      this.detectionBtn = false;
			      this.isShowDownload = false;
			      this.through = false;
			    }
			  })
			},
			//submit xslc
			submibXslc() {
			  hlhttp.post({
			    baseUrl: exclUrl,
			    url: 'resource/customer_upload_data',
			    data: {
			      file_name: this.srcUrl.indexOf('/') > -1 ? this.srcUrl.substr(this.srcUrl.lastIndexOf('/') + 1) : this.srcUrl,
			      is_myself: 'Y'
			    },
			    success: () => {
			      hl.toast('上传成功')
			      this.search()
			      this.importExclClose()
			    }
			  })
			},
			//end
      selectMenuList(){
        this.currentPage = 1
        this.searchData()
      },
      //显示hover
      hoverText(e, v) {
        var s = this.$refs.scrollLeft.scrollLeft;
        var l = e.srcElement.parentNode.offsetLeft - s;
        var t = e.srcElement.parentNode.offsetTop + 40
        this.lefthover = l + 'px';
        this.tophover = t + 'px';
        this.texthover = true;
        this.textLong = v;
      },
      mouseleaveOut() {
        this.lefthover = 0 + 'px';
        this.tophover = 0 + 'px';
        this.texthover = false;
        this.textLong = '';
      },
      goTodetail(id) {
        hlUrlUtil.goTo('customerDetails', {
          'id': id,
          'ddtab': true,
          'page': 'customerMy'
        }, true)
      },
      resetTabbar() {
        this.selectedListMenuCode = []
        this.currentPage = 1
        this.searchData()
      },
      openSearch() {
        if (this.isExtenseFlag == true) {
          this.isExtenseFlag = false;
          return false;
        }
        if (this.isExtenseFlag == false) {
          this.isExtenseFlag = true;
          return false;
        }
      },
      searchData(curPage, limit) {
        var beginDate = this.secondRowBeginDate ? this.secondRowBeginDate + ' 00:00:00' : '#'
        var endDate = this.secondRowEndDate ? this.secondRowEndDate + ' 23:59:59' : '#'
        var self = this;
        var submitData = {
          'keyword': self.keyWord || '#',
          'customer_state': self.selectedCustomerStatu.length ? self.selectedCustomerStatu[0] : '#',
          'customer_type': self.selectedCustomerType.length ? self.selectedCustomerType[0] : '#',
          'industry': self.selectedIndustryType.length ? self.selectedIndustryType[0] : '#',
          'channel_category_code': self.selectedChannelType.length ? self.selectedChannelType[0] : '#',
          'channel_name_code': self.selectedChannelName.length ? self.selectedChannelName[0] : '#',
          'status': self.selectedListMenuCode.length ? self.selectedListMenuCode.join(',') : '#',
          'limit': self.limit[0],
          'page': self.currentPage,
          'columns': self.columns || '#',
          'orders': self.orders || '#',
          'followup_time_begin': beginDate,
          'followup_time_end': endDate,
        }

        hlhttp.get({
          url: 'customer/cmt_user_search',
          data: submitData,
          success: function(data) {
            self.listObj = data
            self.totalCount = data.totalCount
            self.totalPage = data.totalPage
            self.countInfoData = data.countInfo
            self.listMenu.forEach(el => {
              if (el.code == 'FMWF') el['num'] = data.countInfo.FMWF;
              if (el.code == 'FMFI') el['num'] = data.countInfo.FMFI;
              if (el.code == 'FMOWF') el['num'] = data.countInfo.FMOWF;
            })

          }
        })
      },
      //查询
      search() {
        this.currentPage = 1;
        this.limit = ['10'];
        this.searchData()
      },
      reset() {
        this.keyWord = null;
        this.isActiveCode = ''
        this.orders = ''
        this.columns = ''
        this.currentPage = 1
        this.selectedChannelType = []
        this.selectedChannelName = []
        this.selectedCustomerStatu = []
        this.selectedCustomerType = []
        this.selectedIndustryType = []

        this.secondRowBeginDate = ''
        this.secondRowEndDate = ''
        this.rperson = {
          name: null,
          list: [],
          id: null
        };

        this.search()
      },
      selectBlackStatus() {
        if (this.blackStatus == 'Y') this.blackStatus = 'N'
        if (this.blackStatus == 'N') this.blackStatus = 'Y'
      },
      // 获取对接人人员列表
      getRpersonData() {
        var self = this;
        hlhttp.get({
          url: 'tenants/users/_search',
          data: {
            'keyword': self.rpersonKeyword || '#',
            'first_order': 'Y'
          },
          success: function(data) {
            self.rperson.list = data;
            // 自动匹配  当输入的名字跟下拉列表中名字匹配时  则存储ID
            data.forEach(el => {
              if (el.name == self.rpersonKeyword) {
                self.rperson.name = self.rpersonKeyword;
                self.rperson.id = el.id;
              }
            })
          }
        })
      },
      goToAddCustomer() {
        hlUrlUtil.goTo('createCm', {
          page: 'customerMy',
          ddtab: true
        }, true)
        window.sessionStorage.removeItem('RENT_BUSINESS_CUSTOMER')
      },
      getMatchRperson() {
        this.getRpersonData()
      },
      // 设置对接人name，获取id
      setRperson(name, id) {
        this.rperson = {
          name: name,
          list: [],
          id: id
        }
        this.rpersonKeyword = name
      },
      hideRpersonList() {
        this.rperson.list = [];
      },
      selectCustomerStatu(arr) {
        this.selectedCustomerStatu = [arr[0].code]
      },
      selectCustomerType(arr) {
        this.selectedCustomerType = [arr[0].code]
      },
      // 获取产业
      getIndustryType() {
        hlhttp.get({
          url: 'configure/industry/dict',
          success: data => {
            data.unshift({
              'dictName': '全部',
              'dictCode': '#'
            })
            this.industryType = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })
      },
      selectIndustryType(arr) {
        this.selectedIndustryType = [arr[0].code]
      },
      // 渠道分类
      getChannelType() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_CATE'
          },
          success: data => {
            this.channelType = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })
      },
      selectChannelType(arr) {
        this.selectedChannelType = [arr[0].code]
        this.getChannelName()
      },
      // 获取渠道名称
      getChannelName() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH',
            config_name: 'ZS_CHANNEL_NAME',
						parent_dict_code: this.selectedChannelType[0]
          },
          success: data => {
            this.channelName = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);
          }
        })
      },
      selectChannelName(arr) {
        this.selectedChannelName = [arr[0].code]
      },
      //线索来源
      getSJsource() {
        hlhttp.get({
          url: 'configure/dict',
          data: {
            module_code: 'ZHSH0SHJI',
            config_name: 'SJ_SOURCE'
          },
          success: data => {
            data.unshift({
              'dictName': '全部',
              'dictCode': '#'
            })
            this.sourceList = hlArrayUtil.replaceData(data, [{key: 'dictName', rKey: 'name'}, {key: 'dictCode', rKey: 'code'}]);

          }
        })
      },
      selectSJsource(arr) {
        this.selectedSource = [arr[0].code]
      },
      // 获取用户工作组组员
      getPerson() {
        hlhttp.get({
          url: 'data_group/users/_search',
          data: {
            keyword: '#'
          },
          success: data => {
            this.personList = data;
          }
        })
      },
      selectPerNum(arr) {
        this.limit = [arr[0].code]
        this.currentPage = 1
        this.searchData()
      },
      selectDispatchItem(isChecked, i) {
        if (isChecked == 'Y') this.$set(this.listData[i], 'isChecked', 'N');
        if (isChecked == 'N') this.$set(this.listData[i], 'isChecked', 'Y');
        let isAllSelected = true;
        this.listData.forEach(el => {
          if (el.isChecked == 'N') isAllSelected = false
        })
        if (isAllSelected) {
          this.isAllSelected = true;
        } else {
          this.isAllSelected = false;
        }
      },
      closePersonLayer() {
        this.isShowPersonLayer = false;
      },
      confirmDispatchSingleItem() {
        hlhttp.put({
          url: 'customer/biz_oppt_assign',
          data: {
            sj_ids: this.selectedSingleItem.sjId,
            assignee_id: this.selectedSingleItem.id,
            assignee_name: this.selectedSingleItem.name
          },
          success: data => {
            hl.toast('分派成功')
            this.isShowPersonLayer = false;
            this.isShowOperationBar = true;
            this.search()
          }
        })
      },
      dispatchValidate() {
        this.listData.forEach(el => {
          if (el.isChecked == 'Y') {
            if (this.selectedMulItem.sjIds.indexOf(el.sjId) == -1) this.selectedMulItem.sjIds.push(el.sjId)
          }
        })
        if (!this.selectedMulItem.id) {
          hl.toast('请选择分派人')
          return false
        }
        if (!this.selectedMulItem.sjIds) {
          hl.toast('请选择分派项目')
          return false
        }
        return true
      },
      confirmDispatchMulItem() {
        var valid = this.dispatchValidate()
        if (valid) {
          hlhttp.put({
            url: 'customer/biz_oppt_assign',
            data: {
              sj_ids: this.selectedMulItem.sjIds.join(','),
              assignee_id: this.selectedMulItem.id,
              assignee_name: this.selectedMulItem.name
            },
            success: data => {
              hl.toast('分派成功')
              this.isShowPersonLayer = false;
              this.isShowOperationBar = true;
              this.search()
            }
          })
        }
      },
      dispatchBusiness(id) {
        this.selectedSingleItem.sjId = id;
        this.isShowPersonLayer = true;
      },
      showScroll() {
        this.isScroll = true;
      },
      hideScroll() {
        this.isScroll = false;
      },

      //更新时间
      sortBySTTime(item) {
        if(this.dateTimeUpdate.indexOf(item.value) == -1) return
        this.isActiveCode = item.value;
        this.orders = this.orders == 'ASC' ? 'DESC' : 'ASC';
        this.columns = item.orderName
        this.searchData()
      },
      //获取自定义表头配置状态
      configTypeDt() {
        hlhttp.get({
          url: 'configure/customize_column_header/type',
          data: {
            module: 'ZHSH_WDKH'
          },
          success: (data) => {
            this.configType = data.configType;
            this.customizeHeaderDt()
          }
        })
      },
      //获取自定义表头配置信息
      customizeHeaderDt() {
        hlhttp.get({
          url: 'configure/customize_column_header',
          data: {
            module: 'ZHSH_WDKH'
          },
          success: (data) => {
            data.customConfigList.map(item => {
              item.seq = Number(item.seq)
              item.customSeq = Number(item.customSeq)
              item.isActive = 'N'
              if (item.orderFlag == 'Y') {
								this.dateTimeUpdate.push(item.value)
							}
            })
            if (this.configType == 'JD' || this.configType == 'WZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('seq'))
            }
            if (this.configType == 'PZ') {
              data.customConfigList = data.customConfigList.sort(hlArrayUtil.compareAsc('customSeq'))
            }
            this.headArr = JSON.parse(JSON.stringify(data.customConfigList));
            this.sortTableTitle = JSON.parse(JSON.stringify(data.customConfigList));
            this.lrTable()
          }
        })
      },
      //左右表格table
      lrTable() {
        this.leftWidth = 0;
        this.rightWidth = 0;
        this.leftTableArr = [];
        this.rightTableArr = [];
        this.headArr.map(item => {
          if (this.configType == 'JD') {
            if (item.baseFlag == 'Y') {
              this.lrTableDistinguish(item)
            }
          }
          if (this.configType == 'WZ') {
            this.lrTableDistinguish(item)
          }
          if (this.configType == 'PZ') {
            if (item.customShowFlag == 'Y') {
              this.lrTableDistinguish(item)
            }
          }
        })
				this.tbTitleWidthCalculation()
      },
      //左右表格区分
      lrTableDistinguish(item) {
        switch (item.unionTablePart){
        	case '1':
        		this.leftTableArr.push(item)
        		break;
        	case '2':
        		this.rightTableArr.push(item)
        		break;
        	default:
        		break;
        }
      },
      //宽度计算
      tbTitleWidthCalculation() {
				console.log(this.leftTableArr)
        this.leftTableArr.map(item0 => {
          this.leftWidth += Number(item0.styleWidth)
        })
        this.rightTableArr.map(item0 => {
          this.rightWidth += Number(item0.styleWidth)
        })
        this.tbTitleWidth = {
          width: (this.leftWidth + this.rightWidth) + 'px'
        }
        if (this.leftWidth + this.rightWidth < 960) {
          this.leftWidth = '50%'
          this.rightWidth = '50%'
          this.tbTitleWidth = {
            width: '100%'
          }
        }
      },
      //弹窗显示
      showTableLayer() {
        this.isShowTableLayer = true;
      },
      //关闭自定义表头弹窗
      closeTableLayer() {
        this.isShowTableLayer = false;
      },
      //简单完整配置切换
      selectTableType(type) {
        this.configType = type;
        this.changeTableType(type)
        this.updateConfigType()
      },
      //更新自定义表头配置状态
      updateConfigType() {
        hlhttp.put({
          url: 'configure/customize_column_header/type',
          data: {
            module: 'ZHSH_WDKH',
            config_type: this.configType
          },
          success: () => {
            this.configTypeDt()
          }
        })
      },
      //改变头部
      changeTableType(type) {
        if (type == 'JD' || type == 'WZ') {
          this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('seq'))
        }
        if (type == 'PZ') {
          this.headArr = this.headArr.sort(hlArrayUtil.compareAsc('customSeq'))
        }
        this.tbTitleWidthCalculation()
      },
      //显示某个自定义标题
      selectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'Y'
      },
      //关闭某个自定义标题
      cancelSelectedTitleItem(i) {
        this.sortTableTitle[i].customShowFlag = 'N'
      },
      showhighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'Y'
      },
      removehighLightTitleItem(el, i) {
        this.sortTableTitle[i].isActive = 'N'
      },
      //鼠标经过显示scroll
      showScroll() {
        this.isScroll = true;
      },
      //鼠标离开关闭scroll
      hideScroll() {
        this.isScroll = false;
      },
      // 确定提交自定义表格
      confirmSubmitTable() {
        let dataArr = [];
        this.sortTableTitle.map((item, index) => {
          dataArr.push({
            "base_flag": item.baseFlag,
            "seq": item.seq,
            "custom_show_flag": item.customShowFlag,
            "custom_seq": index,
            "custom_display_name": item.customDisplayName ? item.customDisplayName : '#',
            "dict_code": item.dictCode,
            "config_type": item.configType,
            "name": item.name,
            "value": item.value,
            "union_table_part": item.unionTablePart,
            flex: item.flex,
            style_width: item.styleWidth,
            order_flag: item.orderFlag,
            order_name: item.orderName
          })
        })
        hlhttp.put({
          url: 'configure/customize_column_header',
          data: {
            module: 'ZHSH_WDKH',
            custom_config: JSON.stringify(dataArr)
          },
          success: (data) => {
            hl.toast('操作成功')
            this.closeTableLayer()
            this.updateConfigType()
          }
        })
      },
      // 初始化拖动排序
      initSortable() {
        const self = this;
        const el = document.getElementById('sortableTable');
        Sortable.create(el, {
          draggable: 'ul',
          onEnd(evt) {
            const beginIndex = evt.oldIndex;
            const endIndex = evt.newIndex;
            const newArr = JSON.parse(JSON.stringify(self.sortTableTitle));
            if (self.sortTableTitle[beginIndex].unionTablePart == self.sortTableTitle[endIndex].unionTablePart) {
              newArr.splice(endIndex, 0, newArr.splice(beginIndex, 1)[0])
            } else {
              hl.toast('合并表格无法跨表头排序')
            }
            self.sortTableTitle = [];
            self.$nextTick(() => {
              self.sortTableTitle = newArr
            })
          }
        })
      },
      goToDetails(id){
        hlUrlUtil.goTo('customerDetails',{'id':id,'ddtab':true,'page':'customerMy'},true)
      },
      handlePageChange(){
        this.searchData()
      }
    },
    mounted: function() {
      hlSelectUi()
      this.initSortable();
      this.configTypeDt();
      this.getChannelType()
      this.search()
      this.getSJsource()
      this.getIndustryType()
      this.getPerson()
      this.configTypeDt()
			this.ZS_CUSTOMER_STATUS()
			
			
			fileUpload('.upload-filess', uploadUrl, (src) => {
			  if (src.json == undefined) return;
			  if (!(src.json.name.indexOf('xls') > -1)) {
			    hl.toast('请上传正确的模板')
			    return
			  }
			  if (!(src.json.name.indexOf('xlsx') > -1)) {
			    hl.toast('请上传正确的模板')
			    return
			  }
			  this.srcUrl = src.json.url.substr(src.json.url.lastIndexOf('/') + 1);
			  $('.filename-i').val(src.json.name)
			})
    }
  })
}(window))
